// import "whatwg-fetch"; //不用兼容ie8时使用这个
// import "fetch-ie8"; //https://www.npmjs.com/package/fetch-ie8
import axios from "axios";
import storage from "./storage";
import { LOGIN_TOKEN, UN_LOGIN, UNSET_PASSWORD } from "./Const";
import { URL } from "../config/Api";
import { toast } from "./tip";
import { DeviceEventEmitter } from "react-native";
import { getLoginState } from "../util/loginStateManager";

// storage.set(LOGIN_TOKEN, "655448c3-a163-40f7-a5b0-66633524d287");
// storage.set(LOGIN_TOKEN, "b02e45ea-3dd0-4ff0-8d43-7dd7f46ebe2b");
// storage.set(LOGIN_TOKEN, "a14feaa9-f35f-4ddf-b269-704836ec0a9b");

function parseJSON(response) {
  if (response.status === 204 || response.status === 205) {
    return null;
  }
  if (response.data.code == 0) return response.data;
  if (response.data.code == 401) {
    DeviceEventEmitter.emit(UN_LOGIN);
  }
  if (response.data.code == 100012) {
    DeviceEventEmitter.emit(UNSET_PASSWORD);
  }
  //fetch
  else {
    toast(response.data.msg);
  }
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;

  throw error;
}

function request(url, options = {}) {
  const token = storage.get(LOGIN_TOKEN);

  if (token)
    options = {
      ...options,
      headers: {
        ...options.headers,
        "X-BGT-Token": token
      }
    };
  return axios(URL + url, options)
    .then(checkStatus)
    .then(parseJSON)
    .catch(error => {
      if (error.response.data.code == 401) {
        DeviceEventEmitter.emit(UN_LOGIN);
      }
      if (rror.response.data.code == 100012) {
        DeviceEventEmitter.emit(UNSET_PASSWORD);
      }
      if (rror.response.data.code == 502 || response.data.code == 503) {
        alert('系统日常维护中，请稍后再访问。');
      }
    });
}

export default {
  request,
  post: (url, params = {}) => {
    return request(url, {
      method: "post",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      data: params
    });
  },
  get: (url, params = {}) => {
    return request(url, { params });
  },
  delete: (url, params = {}) => {
    const token = storage.get(LOGIN_TOKEN);
    return axios
      .delete(URL + url, {
        params,
        headers: {
          "X-BGT-Token": token
        }
      })
      .then(checkStatus)
      .then(parseJSON)
      .catch(error => {
        if (error.response.data.code == 401) {
          DeviceEventEmitter.emit(UN_LOGIN);
        }
      });
  },

  put: (url, params = {}) => {
    const token = storage.get(LOGIN_TOKEN);
    return axios
      .put(URL + url, params, {
        headers: {
          "X-BGT-Token": token
        }
      })
      .then(checkStatus)
      .then(parseJSON)
      .catch(error => {
        if (error.response.data.code == 401) {
          DeviceEventEmitter.emit(UN_LOGIN);
        }
      });
  }
};
